//
// DBusTransport.cs
//
// Copyright (C) 2008 Lukas Lipka <lukaslipka@gmail.com>
//

using System;
using System.IO;

using NDesk.DBus;

using Dashboard;
using Dashboard.Engine;

namespace Dashboard.Engine.Transports
{
	public class DBusTransport : IComponent
	{
		private const string interface_name = "org.gnome.Dashboard";
		private const string path_name = "/org/gnome/Dashboard/Transport";

		public void Initialize ()
		{
			DBusConnectionHandler connection = new DBusConnectionHandler ();
			Bus.Session.Register (interface_name, new ObjectPath (path_name), connection);
		}

		public void Dispose ()
		{
		}

		private class DBusConnectionHandler : IDBusTransport
		{
			public void Send (byte[] data)
			{
				if (data == null)
					return;

				MemoryStream stream = new MemoryStream (data);
				Message message = null;
				
				try {
					message = Message.Serializer.Deserialize (stream) as Message;
				} catch (Exception e) {
					Engine.Log.Error ("Failed to deserialize message");
					Engine.Log.Error (e);
				}

				if (message != null)
					Engine.MessageBroker.Send (message);
			}
			
			public void Subscribe (string pattern, MessageHandler handler)
			{
				throw new NotImplementedException ();
			}
		}

		public string Name
		{
			get { return "DBusTransport"; }
		}

		public string Description
		{
			get { return "Transports messages to and from the engine over DBus"; }
		}
	}
}
